package me.zhengjie.minbearwcs.serivce.outbound;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.minbearwcs.dao.config.inf.WcsParamConfigDao;
import me.zhengjie.minbearwcs.dao.outbound.inf.OutboundOrderDao;
import me.zhengjie.minbearwcs.entity.DTO.response.Resp;
import me.zhengjie.minbearwcs.entity.DTO.response.RespWithObject;
import me.zhengjie.minbearwcs.entity.DTO.transfer.Tuple;
import me.zhengjie.minbearwcs.entity.PO.config.WcsParamConfig;
import me.zhengjie.minbearwcs.entity.PO.config.WcsParamConfigContentPool;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.OutboundOrder;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.common.OutboundContentPool;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.status.OutboundOrderStatus;
import me.zhengjie.minbearwcs.serivce.mission.generate.MissionGeneratorCollector;
import me.zhengjie.minbearwcs.serivce.mission.generate.type.MissionGenType;
import me.zhengjie.minbearwcs.serivce.mission.locker.StorageLockCollector;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class OutboundDesktopService {

    private final OutboundOrderDao outboundOrderDao;
    private final MissionGeneratorCollector missionGeneratorCollector;
    private final TransactionTemplate transactionTemplate;
    private final WcsParamConfigDao wcsParamConfigDao;

    public Tuple<String> sortOutboundOrder(@RequestBody List<String> outboundOrderList) {
        synchronized (StorageLockCollector.lockStorage5FOr6F) {
            synchronized (StorageLockCollector.lockRestStorage5FOr6F) {
                synchronized (StorageLockCollector.lockBufferStorage5FOr6F) {

                    return transactionTemplate.execute(status -> {
                        try {
                            List<String> alreadyStartOrder = new ArrayList<>();
                            for (String order : outboundOrderList) {
                                OutboundOrder outboundOrder = outboundOrderDao.selectByOrderCode(order);
                                if (OutboundOrderStatus.INIT != outboundOrder.getStatus()) {
                                    alreadyStartOrder.add(order);
                                }
                            }

                            if (!alreadyStartOrder.isEmpty()) {
                                String temp = alreadyStartOrder.stream()
                                        .collect(Collectors.joining("、"));
                                return Tuple.tuple("订单 " + temp + " 已开启，请勿重复操作", false);
                            }

                            for (String orderCode : outboundOrderList) {
                                outboundOrderDao.updateStatusByOutboundOrderCode(
                                        orderCode,
                                        OutboundOrderStatus.PROCESSING
                                );
                            }

                            return missionGeneratorCollector.getGenerator(MissionGenType.OUTBOUND).generate(outboundOrderList);
                        } catch (Exception e) {
                            log.error("出库开启失败", e);
                            return Tuple.tuple("出库开启失败", false);
                        }
                    });


                }
            }
        }


    }


    @Transactional
    public Tuple<String> stockUpOutboundMark(List<String> outboundOrderList) {
        for (String orderCode : outboundOrderList) {
            outboundOrderDao.updateNeedStockUpByOutboundOrderCode(
                    orderCode,
                    OutboundContentPool.OUTBOUND_ORDER_NEED_STOCK_UP
            );
        }
        return Tuple.tuple(null, true);
    }


    public Tuple<String> getOutboundLocation() {
        WcsParamConfig wcsParamConfig = wcsParamConfigDao.selectByKey(WcsParamConfigContentPool.OUTBOUND_DESTINATION_TYPE);
        if (wcsParamConfig == null) {
            return Tuple.tuple(null, false);
        }
        return Tuple.tuple(wcsParamConfig.getConfigValue(), true);
    }


    public Tuple<String> switchOutboundLocation(String outboundLocationType) {
        wcsParamConfigDao.updateByConfigKey(WcsParamConfigContentPool.OUTBOUND_DESTINATION_TYPE, outboundLocationType);
        return Tuple.tuple(null, true);
    }


    // 备货测试触发
    public Tuple<String> stockUpOutboundTest(List<String> outboundOrderList) {
        Boolean execute = transactionTemplate.execute(status -> {
            try {
                for (String orderCode : outboundOrderList) {
                    outboundOrderDao.updateNeedStockUpByOutboundOrderCode(
                            orderCode,
                            OutboundContentPool.OUTBOUND_ORDER_NEED_STOCK_UP
                    );
                }
                return true;
            } catch (Exception e) {
                log.error("触发备货出错", e);
                status.setRollbackOnly();
            }
            return false;
        });

        if (!execute) {
            return Tuple.tuple(null, false);
        }

        return missionGeneratorCollector.getGenerator(MissionGenType.OUTBOUND_STOCK_UP).generate(null);
    }
}
